package com.Aug.controller.user;

import com.Aug.entity.User;
import com.Aug.exception.PasswordIncorrectException;
import com.Aug.exception.UserIsNotExistException;
import com.Aug.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {

    UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type","text/plain;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verify = req.getParameter("verify");

        HttpSession session = req.getSession();
        String verification = (String)session.getAttribute("verification");

        if (!verification.equals(verify)){
            resp.getWriter().write("验证码错误");
            return;
        }

        User user = new User();
        user.setPassword(password);
        user.setName(username);


        try {
            userService.login(user);
            //保存登陆状态
            session = req.getSession();
            session.setAttribute("user",user);
            //页面跳转
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        } catch (UserIsNotExistException e){
            resp.getWriter().write("用户不存在");
        } catch (PasswordIncorrectException e){
            resp.getWriter().write("密码错误");
        }
    }
}
